package com.bbm.communitysystem.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.bbm.communitysystem.core.generate.HeadImg;
import com.bbm.communitysystem.core.oss.OSS;
import com.bbm.communitysystem.domain.OssFile;
import com.bbm.communitysystem.domain.UserInfo;
import com.bbm.communitysystem.domain.bo.UserCredBo;
import com.bbm.communitysystem.domain.bo.UserInfoBo;
import com.bbm.communitysystem.domain.dto.UserInfoDto;
import com.bbm.communitysystem.mapper.UserInfoMapper;
import com.bbm.communitysystem.service.IUserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bbm
 * @since 2025-02-13
 */
@Service
@RequiredArgsConstructor
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {

    private final OSS oss;

    private final HeadImg headImg;

    @Override
    public UserInfoDto CreateUserInfo(UserCredBo userCredBo) {

        UserInfo userInfo = new UserInfo();
        userInfo.setCredId(userCredBo.getId());
        userInfo.setUserEmail("none");
        userInfo.setUserNick(userCredBo.getUserName());
        userInfo.setUserSex(1);
        userInfo.setIsSun(0);
        userInfo.setCommunityId(0);
        userInfo.setUserRoleId("0");
        userInfo.setStatus(1);
        userInfo.setUserBirthDate("2000-01-01");

        try {
             List<OssFile> ossFiles = oss.saveFile("headImg", userCredBo.getId() + "", headImg.generateImg(userCredBo.getUserName()));

             if (ossFiles.isEmpty()) {
                 return null;
             }
             userInfo.setOssId(ossFiles.get(0).getId());
             userInfo.setUserImg(ossFiles.get(0).getClientUrl());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        userInfo.setUpdateBy(userCredBo.getId().toString());
        userInfo.setUpdateTime(System.currentTimeMillis() + "");
        save(userInfo);



        return BeanUtil.copyProperties(userInfo, UserInfoDto.class);
    }

    @Override
    public UserInfoDto PutUserHeadImg(UserInfoBo userIngoBo) {

        List<OssFile> ossFiles = oss.saveFile("headImg", userIngoBo.getUpdateBy(), userIngoBo.getUserImg());

        if (ossFiles.isEmpty()) {
            return null;
        }

        UserInfo userInfo = new UserInfo();

        userInfo.setId(userIngoBo.getId());
        userInfo.setUserImg(ossFiles.get(0).getClientUrl());
        userInfo.setOssId(ossFiles.get(0).getId());


        boolean b = updateById(userInfo);

        if (!b) {
            return null;
        }

        return BeanUtil.copyProperties(userInfo, UserInfoDto.class);
    }
}
